<template>
    <div class="orders-content">
        <div class="orders-header">
            <el-tabs v-model="localStatus" @tab-change="handleStatusChange">
                <el-tab-pane label="全部" name="5"></el-tab-pane>
                <el-tab-pane label="待付款" name="0"></el-tab-pane>
                <el-tab-pane label="待发货" name="1"></el-tab-pane>
                <el-tab-pane label="待收货" name="2"></el-tab-pane>
                <el-tab-pane label="已完成" name="3"></el-tab-pane>
                <el-tab-pane label="已取消" name="4"></el-tab-pane>
            </el-tabs>
            <div class="sort-direction" @click="toggleSortOrder">
                <el-icon class="sort-icon">
                    <SortUp v-if="localIsAsc" />
                    <SortDown v-else />
                </el-icon>
            </div>
        </div>
        <el-table :data="localOrders" style="width: 100%">
            <el-table-column prop="orderNo" label="订单号" width="250" />
            <el-table-column prop="createTime" label="下单时间" width="180" />
            <el-table-column prop="name" label="收货人" width="100" />
            <el-table-column prop="phone" label="联系电话" width="150" />
            <el-table-column prop="statusText" label="状态" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="viewDetail(scope.row.orderNo)">查看详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination 
            v-model:currentPage="localOrderPage" 
            v-model:page-size="localOrderSize" 
            :total="orderTotal"
            layout="prev, pager, next" 
            @current-change="handlePageChange" 
        />

        <!-- 订单详情弹窗 -->
        <el-dialog v-model="dialogVisible" title="订单详情" width="600px">
            <div v-if="orderDetail" class="order-detail">
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="订单号">{{ orderDetail.orderNo }}</el-descriptions-item>
                    <el-descriptions-item label="下单时间">{{ orderDetail.createTime }}</el-descriptions-item>
                    <el-descriptions-item label="收货人">{{ orderDetail.name }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话">{{ orderDetail.phone }}</el-descriptions-item>
                    <el-descriptions-item label="收货地址">{{ orderDetail.address }}</el-descriptions-item>
                    <el-descriptions-item label="订单状态">{{ getStatusText(orderDetail.status) }}</el-descriptions-item>
                    <el-descriptions-item label="总金额">¥{{ orderDetail.totalAmount }}</el-descriptions-item>
                </el-descriptions>

                <div class="product-section">
                    <h4>商品信息</h4>
                    <el-table :data="orderDetail.productList" style="width: 100%">
                        <el-table-column prop="name" label="商品名称" />
                        <el-table-column prop="price" label="单价" width="100">
                            <template #default="scope">
                                ¥{{ scope.row.price }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="quantity" label="数量" width="80" />
                        <el-table-column label="小计" width="100">
                            <template #default="scope">
                                ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { SortUp, SortDown } from '@element-plus/icons-vue'
import orderApi, { OrderResponse, OrderListQuery } from '@/api/order'

const props = defineProps<{
    status: string
}>()

const emit = defineEmits<{
    (e: 'status-change', status: string): void
}>()

const localStatus = ref(props.status || '5')
const localOrders = ref<OrderResponse[]>([])
const localOrderPage = ref(1)
const localOrderSize = ref(10)
const orderTotal = ref(0)
const localIsAsc = ref(false) // 默认降序

// 订单详情相关
const dialogVisible = ref(false)
const orderDetail = ref<OrderResponse | null>(null)

const getStatusText = (status: number) => {
    switch (status) {
        case 0: return '待付款'
        case 1: return '待发货'
        case 2: return '待收货'
        case 3: return '已完成'
        case 4: return '已取消'
        default: return '未知状态'
    }
}

const handleStatusChange = (status: string) => {
    localStatus.value = status
    localOrderPage.value = 1
    emit('status-change', status)
    fetchOrders()
}

const handlePageChange = (page: number) => {
    localOrderPage.value = page
    fetchOrders()
}

const toggleSortOrder = () => {
    localIsAsc.value = !localIsAsc.value
    fetchOrders()
}

// 获取订单列表
const fetchOrders = async () => {
    try {
        const query: OrderListQuery = {
            pageNo: localOrderPage.value,
            pageSize: localOrderSize.value,
            status: localStatus.value !== '5' ? parseInt(localStatus.value) : undefined,
            isAsc: localIsAsc.value
        }

        const res = await orderApi.queryOrderList(query)
        localOrders.value = res.data.data.list.map((order: any) => ({
            ...order,
            statusText: getStatusText(order.status),
            name: order.name, // 确保包含收货人
            phone: order.phone // 确保包含联系电话
        }))
        orderTotal.value = res.data.data.total
    } catch (error) {
        ElMessage.error('获取订单列表失败')
        console.error(error)
    }
}

// 查看订单详情
const viewDetail = async (orderNo: string) => {
    try {
        const res = await orderApi.getOrderItem(orderNo)
        orderDetail.value = {
            ...res.data.data,
            statusText: getStatusText(res.data.data.status)
        }
        dialogVisible.value = true
    } catch (error) {
        ElMessage.error('获取订单详情失败')
        console.error(error)
    }
}

onMounted(() => {
    fetchOrders()
})
</script>

<style scoped>
.orders-content {
    max-width: 1200px;
    margin-left: 10px;
}

.orders-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.sort-direction {
    cursor: pointer;
    margin-right: 20px;
    padding: 5px;
}

.sort-direction:hover {
    background-color: #f5f5f5;
    border-radius: 4px;
}

.el-table .cell {
    white-space: nowrap; /* 防止内容换行 */
}

.order-detail {
    padding: 20px 0;
}

.product-section {
    margin-top: 20px;
}

.product-section h4 {
    margin-bottom: 10px;
    color: #333;
}
</style>